import datetime
from flask import g, request, current_app, jsonify
from info import db
from info.models import House, Order
from info.modules.order import order_blu
from info.utils.common import user_login
from info.utils.response_code import RET


@order_blu.route("/orders", methods=["POST"])
@user_login
def api_orders():

    user = g.user
    house_id = request.json.get("house_id")
    start_date = request.json.get("start_date")
    end_date = request.json.get("end_date")

    if not all([house_id, start_date, end_date]):
        return jsonify(errno=RET.PARAMERR, errmsg="参数错误")

    try:
        house_id = int(house_id)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.PARAMERR, errmsg="参数错误")
    try:
        house = House.query.get(house_id)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg="数据库查询失败")

    startdate = datetime.datetime.strptime(start_date, "%Y-%m-%d")
    enddate = datetime.datetime.strptime(end_date, "%Y-%m-%d")

    order = Order()
    order.user_id = user.id
    order.house_id = house_id
    order.begin_date = startdate
    order.end_date = enddate
    order.days = enddate.day - startdate.day
    order.house_price = house.price
    order.amount = (enddate.day - startdate.day) * house.price

    try:
        db.session.add(order)
        db.session.commit()
    except Exception as e:
        db.session.rollback()
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg="数据库保存失败")

    return jsonify(errno=RET.OK, errmsg="OK")


@order_blu.route("/api/v1.0/orders",methods=["GET"])
@user_login
def order():

    user = g.user
    # 用户订单初始化
    role = request.args.get("role")
    if role == "custom":
        try:
            user_order = Order.query.filter(Order.user_id == user.id).order_by(Order.create_time.desc()).all()
        except Exception as e:
            current_app.logger.error(e)
            return jsonify(errno=RET.DBERR, errmsg="数据库保存失败")

        user_order_li = [order.to_dict() for order in user_order]

        data={"orders":user_order_li}

        return jsonify(data=data, errno=RET.OK,errmsg="OK")

    elif role == "landlord":
        houses = House.query.filter_by(user_id=user.id).all()
        house_ids =[]
        for house in houses:
            house_ids.append(house.id)
        orders = Order.query.filter(Order.house_id.in_(house_ids)).order_by(Order.create_time.desc()).all()

        orders_list =[order.to_dict() for order in orders]

        data={"orders":orders_list}

        return jsonify(data=data, errno=RET.OK,errmsg="OK")


@order_blu.route('/api/v1.0/orders/comment', methods=["PUT"])
@user_login
def set_order_comment():
    """
    评论订单
    :param order_id:
    :return:
    """

    # 获取参数&校验参数
    order_id = request.json.get('order_id')
    comment = request.json.get('comment')
    if not all([order_id,comment]):
        return jsonify(errno=RET.PARAMERR, errmsg='参数不全')
    try:
        order = Order.query.get(order_id)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg='查询数据错误')

    if not order:
        return jsonify(errno=RET.NODATA, errmsg='该订单不存在')

    try:
        order = Order.query.filter(Order.id == order_id, Order.status == "WAIT_COMMENT").first()
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg='查询数据错误')

    if not order:
        return jsonify(errno=RET.DATAERR, errmsg='该订单还不能评价')

    # 通过订单id查询出订单模型
    try:
        house = House.query.filter(House.id==order.house_id).first()
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg='查询数据错误')
    # 更新数据

    order.comment = comment
    order.status = "COMPLETE"
    house.order_count += 1
    # 更新数据库
    try:
        db.session.commit()
    except Exception as e:
        current_app.logger.error(e)
        db.session.rollback()
        return jsonify(errno=RET.DBERR, errmsg='更新数据库失败')

    # 删除redis中缓存的房屋详情信息，因为房屋详情信息已经更新
    # try:
    #     redis_store.delete('house_info_' + house.id)
    # except Exception as e:
    #     current_app.logger.error(e)

    return jsonify(errno=RET.OK, errmsg='OK')


@order_blu.route('/api/v1.0/orders', methods=["PUT"])
@user_login
def set_order_status():

    # 获取当前用户id
    user = g.user

    # 获取参数&校验参数
    order_id = request.json.get('order_id')

    action = request.json.get('action')
    if not all([order_id,action]):
        return jsonify(errno=RET.PARAMERR, errmsg='参数不全')

    if action not in ["accept", "reject"]:
        return jsonify(errno=RET.PARAMERR, errmsg='参数错误')

    try:
        order = Order.query.get(order_id)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg='查询数据错误')

    if not order:
        return jsonify(errno=RET.NODATA, errmsg='该订单不存在')

    try:
        order = Order.query.filter(Order.id == order_id, Order.status == "WAIT_ACCEPT").first()
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg='查询数据错误')

    if not order:
        return jsonify(errno=RET.DATAERR, errmsg='该订单已接单')

    # 通过订单id查询出订单模型
    try:
        house = House.query.filter(House.id==order.house_id).first()
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg='查询数据错误')

    # 判断订单是否存在并且当前房屋的用户id是当前用户id
    if house.user_id != user.id:
        return jsonify(errno=RET.NODATA, errmsg='数据有误')

    if action == "accept":
        # 接单
        order.status = "WAIT_COMMENT"
    elif action == "reject":
        reason = request.json.get('reason')
        if not reason:
            return jsonify(errno=RET.PARAMERR, errmsg='未输入拒单原因')
        # 设置状态为拒单并且设置拒单原因
        order.status = "REJECTED"
        order.comment = reason

    # 保存到数据库
    try:
        db.session.commit()
    except Exception as e:
        current_app.logger.error(e)
        db.session.rollback()
        return jsonify(errno=RET.DBERR, errmsg='保存订单状态失败')

    return jsonify(errno=RET.OK, errmsg='OK')











